package com.woniuxy.portal.model.dto;

import lombok.Data;

import java.util.*;

@Data
public class CartVo {
    private Map<Long,CartItemVo> items=new LinkedHashMap<>();
    private Double totalPrice;
    private Integer amount;
    private Long userId;

    //添加购物项
    public void addItem(CartItemVo cartItem){
        Long bookId = cartItem.getBookId();
        if(items.containsKey(bookId)){
            CartItemVo item = items.get(bookId);
            item.setQuantity(cartItem.getQuantity()+item.getQuantity());
        }else{
            items.put(bookId,cartItem);
        }
        updateAmountAndTotalPrice();
    }

    //更新总价格和总数量
    private void updateAmountAndTotalPrice() {
        Collection<CartItemVo> cartItems = items.values();
        //计算总价格
        this.totalPrice = cartItems.stream().mapToDouble(item -> item.getSum()).sum();
        //计算总数量
        this.amount = cartItems.stream().mapToInt(item -> item.getQuantity()).sum();
    }

    //删除购物项
    public void removeItem(Long bookId) {
        items.remove(bookId);
        updateAmountAndTotalPrice();
    }

    //修改购物项中某件商品的数量
    public void updateItemQuantity(Long bookId, Integer quantity) {
        if (items.containsKey(bookId)) {
            CartItemVo cartItem = items.get(bookId);
            if (quantity <= 0) {
                items.remove(bookId);
            } else {
                cartItem.setQuantity(quantity);
            }
            updateAmountAndTotalPrice();
        }
    }

    //获取购物车中的所有商品
    public List<CartItemVo> getItemList() {
        return new ArrayList<>(items.values());
    }

    //清空购物车
    public void clearCart() {
        items.clear();
        updateAmountAndTotalPrice();
    }

}
